1
第7课:Python模块入门
EvoClass-AI001Lecture 7
00:00

Python模块入门

在Python中,一个模块是一个以.py的文件,用作可重用代码组件(函数、类、变量)的容器。模块是大型程序架构的核心,通过逻辑上分离定义,使开发者能够管理复杂性并提高代码维护性。这一过程类似于数学概念被划分为专门领域的方式(例如,$f(x)$ 在特定定义域 $D$ 中定义)。

1. 模块的作用

模块解决了开发中的三个关键需求:

  • 促进代码复用在多个项目中复用代码,无需重复编写定义。
  • 通过将大型程序划分为易于管理的相关文件,确保代码清晰和结构有序。
  • 防止命名冲突通过为函数和变量定义独立的命名空间来防止命名冲突。

概念性示例:

想象有一个名为utility.py的文件,包含用于计算数学结果的函数。整个文件就是模块,这些函数就是其可访问的内容。

2. 导入方法

Python中的import语句使外部定义对当前脚本可用。所选方法决定了你如何访问组件以及当前程序命名空间如何受到影响。

  • 标准导入:import module_name。需要使用module_name.function()来访问内容。
  • 选择性导入:from module import function。允许直接使用function()而无需模块前缀。
  • 别名导入:import module as alias。提供一个更短、项目特定的昵称以方便使用(例如,import numpy as np)。
标准库重点
Python 包含一个庞大的标准库内置模块(如 'os'、'sys'、'random'、'math')。学会使用这些可复用的模块对于高效开发至关重要,并能节省大量时间。
Question 1
If you use import math, how must you call the sqrt function to calculate $\sqrt{25}$?
sqrt(25)
math.sqrt(25)
math::sqrt(25)
use math sqrt
Question 2
Which benefit of using modules addresses the issue of having multiple functions named process_data in a large application?
Code execution speed
Preventing Naming Collisions
Automatic debugging
Question 3
What happens to a module file the second time you attempt to import it in the same running program?
It is imported again, executing all top-level code.
The import fails with an error.
Python recognizes it is already loaded and skips execution.
Only variables are reloaded.